package com.gwtplatform.samples.basic.client.response;

import com.google.inject.Inject;

import com.guit.client.GuitPresenter;
import com.guit.client.async.AbstractAsyncCallback;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.binder.ViewHandler;
import com.guit.client.place.Place;
import com.guit.client.place.PlaceName;
import com.gwtplatform.samples.basic.client.HasInnerHTML;
import com.gwtplatform.samples.basic.client.HasInnerText;
import com.gwtplatform.samples.basic.client.attacher.RootPanelAttacher;
import com.gwtplatform.samples.basic.client.main.MainPresenter;
import com.gwtplatform.samples.basic.client.response.ResponsePresenter.ResponseBinder;
import com.gwtplatform.samples.basic.shared.SendTextToServerAction;
import com.gwtplatform.samples.basic.shared.SendTextToServerResult;

@PlaceName("response")
public class ResponsePresenter extends GuitPresenter<ResponseBinder> implements Place<String> {

    public static interface ResponseBinder extends GuitBinder<ResponsePresenter>{
    }

    @ViewField
    HasInnerText textToServer;
    
    @ViewField
    HasInnerHTML serverResponse;
    
    private final RootPanelAttacher attacher;

    @Inject
    public ResponsePresenter(RootPanelAttacher attacher) {
        this.attacher = attacher;
    }
    
    @ViewHandler
    protected void close$click() {
        placeManager.go(MainPresenter.class);
    }

    @Override
    public void go(String name) {
        attacher.attach(getView());
        textToServer.setInnerText(name);
        
        serverResponse.setInnerHTML("Loading...");
        commandService.execute(new SendTextToServerAction(name), new AbstractAsyncCallback<SendTextToServerResult>() {
            @Override
            public void success(SendTextToServerResult result) {
                serverResponse.setInnerHTML(result.getResponse());
            }
            
            @Override
            public void failure(Throwable caught) {
                serverResponse.setInnerHTML(caught.toString());
            }
        });
    }
}
